package com.zcccccy.rocketmq.producer.config;

import com.zcccccy.rocketmq.producer.config.properties.ProducerProperties;
import org.apache.rocketmq.client.apis.ClientConfiguration;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 生产者创建
 * 
 * @projectName: zcccccy
 * @packageName: com.zcccccy.extend.rocketmq.producer.config
 * @author: zcy
 * @createTime: 2024/1/29
 * @productName: For Mac IntelliJ IDEA
 */
@Configuration
public class ProducerConfig {

    private static final Logger log = LoggerFactory.getLogger(ProducerConfig.class);

    /**
     * 远程调用连接信息
     */
    public static Producer producer;

    @Autowired
    private ProducerProperties producerProperties;

    @Bean
    public Producer builderProducer() {

        log.info("==============》 开始初始化生产者 《===================");

        try {

            final ClientServiceProvider provider = ClientServiceProvider.loadService();

            // 构建连接信息
            ClientConfiguration configuration = ClientConfiguration.newBuilder()
                // 端点信息
                .setEndpoints(producerProperties.getEndpoints())
                // 构建
                .build();

            // 初始化Producer时需要设置通信配置以及预绑定的Topic。
            producer = provider.newProducerBuilder()
                // TODO 生产者主题预绑定多个，可发送不同主题消息以及不同消息类型消息
                // 主题
                .setTopics(producerProperties.getTopicList().toArray(new String[0]))
                // 连接信息
                .setClientConfiguration(configuration)
                // 最大重试次数
                .setMaxAttempts(producerProperties.getMaxAttempts())
                .build();

            log.info("==============》 初始化生产者成功：{} ", producer);

        } catch (ClientException e) {

            log.info("==============》 初始化生产者失败：{} ", e.getMessage());
            e.printStackTrace();
        }

        return producer;
    }
}
